package com.mojo.openapi.controller;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SignatureUtils {

    // 生成动态签名
    public static String generateSignature(Map<String, String> params) {
        // 将参数名按照字典序排序
        List<String> paramList = new ArrayList<>(params.keySet());
        Collections.sort(paramList);

        // 拼接参数名与参数值
        // 拼接参数名与参数值
        StringBuilder sb = new StringBuilder();
        for (String key : paramList) {
            sb.append(key).append("=").append(params.get(key)).append("&");
        }
        String toSign = sb.toString();
        // 去除最后一个"&"
        toSign = toSign.substring(0, toSign.length() - 1);

        String signature = "";

        try {
            // 计算SHA-256哈希值作为签名
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(toSign.getBytes());
            byte[] digest = md.digest();
            signature = bytesToHex(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return signature;
    }

    // A系统验签
    public static boolean verifySignature(Map<String, String> params, String appSecret, String signature) {
        // 生成参数的签名值
        String generatedSignature = generateSignature(params);
        // 使用应用密钥生成预期的签名值
        String expectedSignature = generateSignatureWithAppSecret(generatedSignature, appSecret);
        System.out.println("expectedSignature >>:" + expectedSignature);
        // 比较生成的签名值与预期的签名值是否相等
        return expectedSignature.equals(signature);
    }

    // 使用应用密钥生成签名值
    private static String generateSignatureWithAppSecret(String content, String appSecret) {
        try {
            // 计算内容和应用密钥的SHA-256哈希值作为签名
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update((content + appSecret).getBytes());
            byte[] digest = md.digest();
            return bytesToHex(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    // 将字节数组转换为十六进制字符串表示
    private static String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }

    public static void main(String[] args) {
        Map<String, String> params = new HashMap<>();
        params.put("a", "1");
        params.put("b", "2");
        params.put("c", "3");
        String signature = generateSignature(params);
        System.out.println("Generated Signature: " + signature);
        System.out.println("验签结果: " + verifySignature(params, "appSecret", signature));
    }
}
